package com.bd.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bd.wechat.constants.CacheConstants;
import com.bd.wechat.core.LoginMember;
import com.bd.wechat.core.exception.ServiceException;
import com.bd.wechat.entity.Member;
import com.bd.wechat.entity.request.LoginRequest;
import com.bd.wechat.mapper.MemberMapper;
import com.bd.wechat.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bd.wechat.utils.JwtTokenUtil;
import com.bd.wechat.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员用户 服务实现类
 * </p>
 *
 * @author linhs
 * @since 2024-11-21
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    PasswordEncoder encoder;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    public String login(LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getAccount(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(authentication.getName());

        return token;
    }


    @Override
    public void register(Member member) {

        Integer memberCount = count(new LambdaQueryWrapper<Member>().eq(Member::getAccount, member.getAccount()));
        if (memberCount > 0) {
            throw new ServiceException("用户名已存在");
        }

        member.setPassword(encoder.encode(member.getPassword()));
        member.setCreateTime(LocalDateTime.now());
        member.setUpdateTime(LocalDateTime.now());
        member.setIsAdmin(0);
        boolean save = save(member);
        if (!save) {
            throw new ServiceException("注册失败");
        }
    }

    @Override
    public LoginMember getInfo() {
        return SecurityUtils.getLoginUser();
    }
}
